package com.example;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: wyp
 * @Date: 2021/9/9 13:55
 * 可重入锁
 *
 */
public class ReentrantLockDemo {
    public static void main(String[] args) {
        Register register = new Register();

        new Thread(()->{
            register.sendMsg();
        },"thread1").start();

        //线程2由于sendEmail()被线程1锁持有，需要等线程1释放才能获取。
        new Thread(()->{
//            register.sendMsg();
            register.sendEmail();
        },"thread2").start();



        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("=======================================");
        new Thread(()->{
            register.sendMsgReentrantLock();
        },"thread3").start();

        new Thread(()->{
            register.sendMsgReentrantLock();
        },"thread4").start();
    }
}
class Register{
    public synchronized void sendMsg(){
        System.out.println(Thread.currentThread().getName()+" sendMsg!");
        sendEmail();
    }
    public synchronized void sendEmail(){
        System.out.println(Thread.currentThread().getName()+" sendEmail!");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Lock lock = new ReentrantLock();

    public void sendMsgReentrantLock(){
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName()+" sendMsg!");
            sendEmailReentrantLock();
        }finally {
            lock.unlock();
        }
    }
    public void sendEmailReentrantLock(){
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName()+" sendEmail!");
        }finally {
            lock.unlock();
        }
    }
}
